package net.miranti.client.view;

import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.MenuBar;
import com.google.gwt.user.client.ui.MenuItem;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;

public class ContextualPanel extends Composite {
	private PopupPanel popupPanel;
	private MenuBar menubar;
	private Widget contentWidget;

	public ContextualPanel(PopupPanel popupPanel, Widget w) {
		SimplePanel panel = new SimplePanel();
		panel.setSize("100%", "100%");
		contentWidget = w;
		panel.add(w);
		initWidget(panel);

		this.popupPanel = popupPanel;
		sinkEvents(Event.ONMOUSEUP | Event.ONCONTEXTMENU);
		popupPanel = new PopupPanel();
		menubar = new MenuBar(true);
	}
	
	public void addContextMenuItem(String label, Command command) {
		menubar.addItem(new MenuItem(label, command));
	}
	
	@Override
	public void onBrowserEvent(Event event) {
		event.preventDefault();
		event.stopPropagation();
		if (DOM.eventGetType(event)==Event.ONMOUSEUP) {
			if (DOM.eventGetButton(event)==Event.BUTTON_RIGHT) {
				popupPanel.setWidget(menubar);
				popupPanel.setPopupPosition(event.getClientX(), event.getClientY());
				popupPanel.show();
			}
		}
	}

	public<T extends Widget> T getContentWidget() {
		return (T) contentWidget;
	}

	public void setContentWidget(Widget contentWidget) {
		this.contentWidget = contentWidget;
	}
}